const {URL} = require('url');
let rp = require('request-promise');
let config = require("../config/wechat");
let APPID = config.appID;
let SECRET = config.appsecret;
let baseUrl = config.baseUrl;
module.exports = {
    async index(ctx, next) {
        let comeFromUrl = myU.getParams(ctx, "comeFromUrl");
        let scopeType = myU.getParams(ctx, "scopeType");
        let REDIRECT_URI = encodeURIComponent(baseUrl + "/wechat/getInfo?comeFromUrl=" + comeFromUrl + "&scopeType=" + scopeType);
        // console.log(1111,REDIRECT_URI);
        let STATE = scopeType; //STATE值为1,则需要用户授权可以获取头像,昵称等,为0则只拿到openid
        let SCOPE = STATE == 1 ? "snsapi_userinfo" : "snsapi_base";
        ctx.redirect(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}&state=${STATE}#wechat_redirect`)
    },
    async getInfo(ctx, next) {
        //1. 获取code值
        let CODE = myU.getParams(ctx, "code");
        // console.log("code",CODE);
        let scopeType = myU.getParams(ctx, "state"); //1表示获取用户昵称和头像,0表示只获取openId
        let comeFromUrl = myU.getParams(ctx, "comeFromUrl");
        try {
            if (!CODE) {
                ctx.body = myU.jsonIfy(0, "code值获取失败");
                return;
            }
            // console.log("code值",CODE);
            //2. 获取access_token,这里非基础接口用的那个access_token
            let accessStr = await rp({

                url: `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${SECRET}&code=${CODE}&grant_type=authorization_code`
            })

            let accessJson = JSON.parse(accessStr);
            // 如果获取access_token有错误
            if (accessJson.errcode) {
                ctx.body = myU.jsonIfy(0, accessJson.errmsg);
                return;
            }
            let ACCESS_TOKEN = accessJson.access_token;
            //这里已经拿到了openid了,如果你是静默授权,那到这里就结束了
            let OPENID = accessJson.openid;
            let userInfo = {};
            userInfo.openid = OPENID;
            //3. 如果你要获取更多用户信息
            // console.log(2222,scopeType);
            if (scopeType == 1) {
                let userRes = await rp({
                    url: `https://api.weixin.qq.com/sns/userinfo?access_token=${ACCESS_TOKEN}&openid=${OPENID}&lang=zh_CN`
                })
                userRes = JSON.parse(userRes)
                if (userRes.errcode) {
                    ctx.body = userRes.errmsg;
                    return;
                }
                userInfo = userRes;
            }
            // console.log("userInfo",userInfo);
            let saveInfo = {
                openid: userInfo.openid,
                nickname: userInfo.nickname,
                sex: userInfo.sex,
                headimgurl: userInfo.headimgurl
            }
            saveInfo = encodeURIComponent(JSON.stringify(saveInfo));
            let redirectUrl = new URL(comeFromUrl);
            redirectUrl.search += (redirectUrl.search ? "&" : "?") + ("userInfo=" + saveInfo)
            ctx.redirect(redirectUrl);
            await next();
        } catch (e) {
            ctx.redirect(comeFromUrl);
            await next();
        }

    }
}